package com.woniu.converter;

import com.woniu.entity.User;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Type;

public class MyConverter  extends AbstractHttpMessageConverter<User> {
    @Override
    protected boolean supports(Class<?> aClass) {
        return User.class==aClass;
    }

    @Override
    protected User readInternal(Class<? extends User> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        InputStream body = httpInputMessage.getBody();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        User user = new User();
        while (body.available()!=0){
            int read = body.read();
            byteArrayOutputStream.write(read);
        }
        byte[] bytes = byteArrayOutputStream.toByteArray();
        String s = new String(bytes,"utf8");
        String[] split = s.split("[||]{1}");
        for (int i = 0; i < split.length; i++) {
            if ( !split[i].contains(":")){
                continue;
            }
            String[] split1 = split[i].split(":");
            Field[] declaredFields = aClass.getDeclaredFields();
            for (int i1 = 0; i1 < declaredFields.length; i1++) {
                if (declaredFields[i1].getName().contains(split1[0])){
                    split1[1]=split1[1].trim();
                    declaredFields[i1].setAccessible(true);
                    try {
                        if (split1[0].equals("id")||split1[0].equals("balance")){
                            declaredFields[i1].set(user,Integer.valueOf(split1[1]));
                        }else {
                            declaredFields[i1].set(user,split1[1]);
                        }

                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }

            }
        }

        return user;
    }

    @Override
    protected void writeInternal(User user, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        String s="";
        httpOutputMessage.getBody().write(s.getBytes());
    }
}
